/**
 * upload 扩展及初始化
 * @author zxj
 */
 
(function ($){
	
	/** 属性注解
		Browse_button://触发浏览文件按钮标签的唯一id,,在flash、html5、和silverlight中能找到触发事件的源（我理解的，这个参数在队列部件不需要参见）      
		Container: 展现上传文件列表的容器，[默认是body]
		chunk_size：当上传文件大于服务器接收端文件大小限制的时候，可以分多次请求发给服务器，如果不需要从设置中移出
		drop_element：当浏览器支持拖拽的情况下，能够文件拖放到你想要的容器ID里
		file_data_name：设置上传字段的名称。默认情况下被设置为文件。（我试验了没找到该如何使用它，暂且不提）
		filters:选择文件扩展名的过滤器,每个过滤规则中只有title和ext两项[{title:'', extensions:''}]
		flash_swf_url:flash文件地址
		headers：自定义的插入http请求的键值对
		max_file_size：最大上传文件大小（格式100b, 10kb, 10mb, 1gb）
		multipart：布尔值，如果用mutlipart 代替二进制流的方式，在webkit下无法工作
		multipart_params： 跟 multipart关联在一起的键值对
		multi_selection： 多选对话框
		resize：修改图片属性 resize: {width: 320, height: 240, quality: 90}
		runtimes:上传插件初始化选用那种方式的优先级顺序，如果第一个初始化失败就走第二个，依次类推
		required_features：需要那些特性，才能初始化插件
		url：上传服务器地址
		unique_names：是否生成唯一的文件名，避免与服务器文件重名
		urlstream_upload：布尔值 如果是flash上传应该用URLStream 代替FileReference.upload
	 */
	var zcUploadPath = ""; //相对路径
	var zcUploadOption  ={loaded:false}; //xml对应的 属性
	$.fn.zcinitupload = function(options){
		//必须项目：path
		if(options.path){
			zcUploadPath = options.path;
		}else{
			alertError("初始化 上传插件失败 请设置相对路径 path 的值!");
		}
		if(options.fileType && fileType!=""){
			
		}
		document.write("<link rel='stylesheet' href='"+zcUploadPath+"/js/jquery.plupload.queue/css/jquery.plupload.queue.css' type='text/css' media='screen' />");
		document.write("<script src='"+zcUploadPath+"/js/plupload.full.min.js'></script>");
		document.write("<script src='"+zcUploadPath+"/js/jquery.plupload.queue/jquery.plupload.queue.js'></script>");
		document.write("<script src='"+zcUploadPath+"/js/i18n/zh_CN.js'></script>");
	}
	

	/**
	 * 必须填：url  服务器处理地址
	 */
	$.fn.zcplupload = function(options){
		
		//遍历传递过来的 参数键值对  重新拼装url
		function iterKeyValue(param){
			var temp = ""; 
			for(var i in param){
				temp += "&"+i+"="+param[i]; 
			} 
			return temp;
		}
		if(options.plugPath== undefined){
			alertError("控件无法初始化  请指定upload.xml 所在目录!");
			return ;
		}
		if(options.params){
			options.url=options.url+"?plugPath="+options.plugPath+iterKeyValue(options.params);
		}else{
			options.url=options.url+"?plugPath="+options.plugPath;
		}
		
		//filters
		var mfilters=[];
		
		var  queueOb = $(this);
		// 上传成功文件数组
		var files = [];
		// 上传出错文件数组
		var errors = [];
		//初始化 upload.xml
		if(!zcUploadOption.loaded){
			$.ajax({
				 url: zcUploadPath+"/upload.xml",
				 type: "POST",
				 dataType: "xml",
				 success: function(data,textStatus){
					 if(options.fileType){
							if(options.fileType == 'img'){
								mfilters[0]= { title : "图片"+$(data).find("params").find("allow-image").text(), extensions :  $(data).find("params").find("allow-image").text()};
							}else if(options.fileType='file'){
								mfilters[0]= {title : "文件"+$(data).find("params").find("allow-file").text(), extensions : $(data).find("params").find("allow-file").text()};
							}else{
								 mfilters =  [
												{title : "图片", extensions : $(data).find("params").find("allow-image").text()},
												{title : "文件", extensions : $(data).find("params").find("allow-file").text()}
											]; 
							}
					 }else{
						 mfilters =  [
										{title : "图片", extensions : $(data).find("params").find("allow-image").text()},
										{title : "文件", extensions : $(data).find("params").find("allow-file").text()}
									];
					 }
					 var optionXml = {
					    loaded:true,
						runtimes : $(data).find("params").find("runtimes").text(),
						url:$(data).find("params").find("url").text(),
						unique_names : true,
						multiple_queues : true,
						rename:true,
						multi_selection:true,//多选对话框
						max_file_size:$(data).find("params").find("allow-size").text()+'m',
						filters :  mfilters,
						flash_swf_url : zcUploadPath+'/js/Moxie.swf',
						silverlight_xap_url : zcUploadPath+'/js/Moxie.xap',
						uploadParams:{},
						init : {
							//文件上传成功的时候触发
							FileUploaded : function(uploader, file, response) {
								
								if (response.response) {
									var rs = $.parseJSON(response.response);
									if (rs.code=="200") {
										files.push(file.name);
									} else {
										errors.push(file.name+" "+rs.result);
									}
								}
							},
							//当队列中所有文件被上传完时触发
							UploadComplete : function(uploader, fs) {
								var e = errors.length ? ",失败" + errors.length + "个(" + errors.join("、") + ")。" : "。";
								if(errors.length>0){
									var errStr = "";
									for(var i=0;i<errors.length;i++){
										errStr+=errors[i]+" \n";
									}
									alertError("上传失败："+errors.length+"个 \n"+errStr);
								}else{
									alertShow("上传完成！共" + fs.length + "个。成功" + files.length+ e);
								}
								$('#fileUploadTabs').tabs('select', 1);
							},
							PostInit: function() {
								// Called after initialization is finished and internal event handlers bound
							},
							Browse: function(up) {
				                // Called when file picker is clicked
				            },
				            Refresh: function(up) {
				                // Called when the position or dimensions of the picker change
				            },
				            StateChanged: function(up) {
				                // Called when the state of the queue is changed
				            },
				            QueueChanged: function(up) {
				                // Called when queue is changed by adding or removing files
				            },
							OptionChanged: function(up, name, value, oldValue) {
								// Called when one of the configuration options is changed
							},
							BeforeUpload: function(up, file) {
								// Called right before the upload for a given file starts, can be used to cancel it if required
							},
				            UploadProgress: function(up, file) {
				                // Called while file is being uploaded
				            },
							FileFiltered: function(up, file) {
								// Called when file successfully files all the filters
							},
				            FilesAdded: function(up, files) {
				                // Called when files are added to queue
				            },
				            FilesRemoved: function(up, files) {
				                // Called when files are removed from queue
				            },
				            ChunkUploaded: function(up, file, info) {
				                // Called when file chunk has finished uploading
				            },
							Destroy: function(up) {
								// Called when uploader is destroyed
							},
							//上传出错的时候触发
							Error : function(l, o) {
								var m = o.file, n;
								if(m){
									n = o.message;
									if(o.details){
										n += " (" + o.details + ")";
									}
									if (o.code == plupload.FILE_SIZE_ERROR) {
										alertError(m.name+'过大，上传限制：'+$(data).find("params").find("allow-size").text()+'m'+'m');
									}
									if (o.code == plupload.FILE_EXTENSION_ERROR) {
										alertError("Error: Invalid file extension: "+ m.name);
									}
									m.hint = n;
									c("#" + m.id).attr("class","plupload_failed").find("a").css("display","block").attr("title", n);
									}
								}
						  }
					 	
					 };
					 $.extend(zcUploadOption, optionXml);
					 $.extend(zcUploadOption, options);
					 queueOb.pluploadQueue(zcUploadOption);
				 },
				 error:function(XMLHttpRequest, textStatus, errorThrown) {
					  // 通常情况下textStatus和errorThown只有其中一个有值 
					  // the options for this ajax request
					 var defaultOption={
								runtimes : 'flash,html4,html5',
								url : '/upload/uploadFiles.do',
								chunk_size : '1mb',
								unique_names : true,
								multiple_queues : true,
								rename:true,
								multi_selection:true,//多选对话框
								filters : {
									max_file_size : '10mb',
									mime_types: [
										{title : "Image files", extensions : "jpg,gif,png"},
										{title : "Zip files", extensions : "zip"}
									]
								},
								resize : {width : 320, height : 240, quality : 90},
								flash_swf_url : zcUploadPath+'/js/Moxie.swf',
								silverlight_xap_url : zcUploadPath+'/js/Moxie.xap'
					};
					$.extend(defaultOption, options);
					alertError("载入上传组件XML失败，启用默认配置!");
					queueOb.pluploadQueue(zcUploadOption);
				 }
			});
		}else{
			$.extend(zcUploadOption, options);
			queueOb.pluploadQueue(zcUploadOption);
		}
	}
	
	
})(jQuery);
